"""
@Date :2024/06/12
"""
import ujson
import _thread
import app_network
from umqtt.simple import MQTTClient
import time
import machine
import ubinascii



get_topic = "attributes/push" 
post_topic = "attributes"


# 定义subcribe的回调函数
def on_subcribe(topic,msg):
    data = ((topic, msg))
    # print(data)
    payload = data[1]
    print(payload,type(payload))
    try:
        cloudmsg = ujson.loads(payload)
    except Exception :
         print("this is not json type!!!")
    else:
        if isinstance(cloudmsg,dict):      #检查收到的数据是否是标准的json格式
            if "key" in cloudmsg:          #平台设置
                print('key')

      
#mqtt数据接收监测
def mqttloop_func(delay, id):
    global client
    n= 0
    while True:
        time.sleep_ms(delay)
        try:
            n+=1
            client.check_msg()
            # print(n)
            if n>=10:
                client.ping()
                n = 0
                print('ping')
        except:
            print("mqtt disconnect!")
            client.disconnect()
            mqtt_reconnect()


#mqtt重新连接
def mqtt_reconnect(mqttaddr,AccessToken, ProjectKey,serverport):
    global client
    client_id = ubinascii.hexlify(machine.unique_id())
    client = MQTTClient(client_id, mqttaddr,serverport, AccessToken, ProjectKey,60) 
    client.set_callback(on_subcribe)
    client.connect() 
    client.subscribe(get_topic)
    update()  


#mqtt首次连接
def mqtt_connect(mqttaddr, AccessToken, ProjectKey,serverport):
    mqtt_reconnect(mqttaddr, AccessToken, ProjectKey,serverport)
    _thread.start_new_thread(mqttloop_func,(1500, 1))  #创建mqtt接收数据任务，1.5s一次


#上传
def update(key='switch',val=''):
    global client
    send_data = {
        key:val
        }
    MSG = ujson.dumps(send_data)
    client.publish(topic=post_topic, msg =MSG, retain=False,qos=0)


       
